#include "PoolManager.h"
#include "Grid.h"
#include "GameWorld.h"

int* PoolManager::m_Map = NULL;
int PoolManager::GridWidth = NULL;
int PoolManager::GridHeight = NULL;

PoolManager::PoolManager()
{}

void PoolManager::CreatePools(Grid& grid)
{
	m_Map = (int*)calloc(grid.Width()*grid.Height(), sizeof(int));

	GridWidth = grid.Width();
	GridHeight = grid.Height();
	for(int i = 0; i < grid.Width(); i++)
	{
		for(int j = 0; j < grid.Height(); j++)
		{
			m_Map[Index(j, i, grid.Width())] = grid.GetGrid()[j][i].back();
		}
	}

	int WaterID = ImageManager->GetImageID("water");

	for(int i = 0; i < grid.Width(); i++)
	{
		for(int j = 0; j < grid.Height(); j++)
		{
			if(m_Map[Index(j, i, grid.Width())] == WaterID)
			{
				GameRectangle WaterBounds(i*TILE_DIMENSIONS, j*TILE_DIMENSIONS, TILE_DIMENSIONS, TILE_DIMENSIONS);
				m_Pools.push_back(new Pool(WaterBounds));
			}
		}
	}

	// Remove the pools that are adjacent only to water
	m_Pools.remove_if(IsAdjacentOnlyToWater);

	AddPools();
	free(m_Map);

}

void PoolManager::AddPools()
{
	list<Pool*>::iterator CurPool = m_Pools.begin();
	while(CurPool != m_Pools.end())
	{
		WorldMap->GetPartition().AddPool(*CurPool);
		CurPool++;
	}
}

void PoolManager::RenderPools()
{
	list<Pool*>::iterator CurPool = m_Pools.begin();
	while(CurPool != m_Pools.end())
	{
		(*CurPool)->RenderBox();
		CurPool++;
	}
}

bool PoolManager::IsAdjacentOnlyToWater(Pool* pool)
{
	Vector2D Loc = pool->Location();
	int row = Loc.y / TILE_DIMENSIONS;
	int col = Loc.x / TILE_DIMENSIONS;

	// If this part is next to only water.

	bool AdjacentOnlyToWater = true;
	int WaterID = ImageManager->GetImageID("water");

	if(col > 0)
		if(m_Map[Index(row, col - 1, GridWidth)] != WaterID)
			AdjacentOnlyToWater = false;

	if(col < GridHeight - 1)
		if(m_Map[Index(row, col + 1, GridWidth)] != WaterID)
			AdjacentOnlyToWater = false;


	if(row > 0)
	{
		if(m_Map[Index(row - 1, col, GridWidth)] != WaterID)
			AdjacentOnlyToWater = false;

		if(col > 0)
			if(m_Map[Index(row - 1, col - 1, GridWidth)] != WaterID)
				AdjacentOnlyToWater = false;

		if(col < GridWidth - 1)
			if(m_Map[Index(row - 1, col + 1, GridWidth)] != WaterID)
				AdjacentOnlyToWater = false;
	}



	if(row < GridWidth - 1)
	{
		if(m_Map[Index(row + 1, col, GridWidth)] != WaterID)
			AdjacentOnlyToWater = false;

		if(col > 0)
			if(m_Map[Index(row + 1, col - 1, GridWidth)] != WaterID)
				AdjacentOnlyToWater = false;

		if(col < GridWidth - 1)
			if(m_Map[Index(row + 1, col + 1, GridWidth)] != WaterID)
				AdjacentOnlyToWater = false;
	}




	return AdjacentOnlyToWater;

}